package ru.susu.algebra.pair;

import java.util.Map;

import org.apache.commons.lang.ObjectUtils;

import com.google.common.base.Function;

/**
 * @author akargapolov
 * @since: 26.02.2009
 */
public class Pair<K, V> implements Comparable<Pair<K, V>>, Map.Entry<K,V>
{
	private K _key;
	private V _value;

	public Pair(K key, V value)
	{
		_key = key;
		_value = value;
	}

	public static <KK, VV> Pair<KK, VV> pair(KK key, VV value)
	{
		return new Pair<KK, VV>(key, value);
	}

	@Override
	@SuppressWarnings("unchecked")
	public int compareTo(Pair<K, V> pair)
	{
		int res1 = ((Comparable<K>)_key).compareTo(pair._key);
		if (res1 == 0)
		{
			return ((Comparable<V>)_value).compareTo(pair._value);
		}
		return res1;
	}

	public V getValue()
	{
		return _value;
	}

	public V setValue(V value)
	{
		_value = value;
		return _value;
	}

	public K getKey()
	{
		return _key;
	}

	public void setKey(K key)
	{
		_key = key;
	}

	@Override
	public int hashCode()
	{
		final int prime = 31;
		int result = 1;
		result = prime * result + ((_key == null) ? 0 : _key.hashCode());
		result = prime * result + ((_value == null) ? 0 : _value.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj)
	{
		if (this == obj)
		{
			return true;
		}
		if (obj == null)
		{
			return false;
		}
		if (getClass() != obj.getClass())
		{
			return false;
		}
		@SuppressWarnings("unchecked")
		Pair other = (Pair) obj;
		return ObjectUtils.equals(_key, other._key) && ObjectUtils.equals(_value, other._value);
	}

	@Override
	public String toString()
	{
		return "[ " + _key + " : " + _value + " ]";
	}

	static public class KeyFunction<T> implements Function<Map.Entry, T>
	{
		@Override
		public T apply(Map.Entry entry)
		{
			return (T)entry.getKey();
		}
	}
}
